//
//  ViewController.m
//  Network
//
//  Created by mac on 16/11/17.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "ViewController.h"

@interface ViewController () <NSURLSessionDataDelegate>
{
    NSMutableAttributedString *attString;
}
@property (weak, nonatomic) IBOutlet UIProgressView *progreess;
@property (weak, nonatomic) IBOutlet UILabel *label;
@property (weak, nonatomic) IBOutlet UIButton *btn;
@property (weak, nonatomic) IBOutlet UIImageView *imageVi;
@property (strong,nonatomic) NSMutableData *filedata;

@end

@implementation ViewController


- (IBAction)start:(id)sender
{
    if(!self.filedata){
    
    NSURL *url = [NSURL URLWithString:@"http://image.baidu.com/search/down?tn=download&word=download&ie=utf8&fr=detail&url=http%3A%2F%2Fwww.bz55.com%2Fuploads%2Fallimg%2F150612%2F139-150612164602-50.jpg&thumburl=http%3A%2F%2Fimg1.imgtn.bdimg.com%2Fit%2Fu%3D1973941799%2C1503249452%26fm%3D21%26gp%3D0.jpg"];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    NSURLSessionDataTask *task = [session dataTaskWithURL:url];
    [task resume];
        
    }
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    float i =   (float)dataTask.countOfBytesReceived / (float)dataTask.countOfBytesExpectedToReceive;
    self.progreess.progress  = i;
    
    NSString *string = [NSString stringWithFormat:@"％%3.2f",i*100];

    [attString replaceCharactersInRange:NSMakeRange(1, attString.length) withString:string];
    [attString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(2, attString.length - 1)];
    
//    self.label.attributedText = attString;
    if(!self.filedata)
    {
        self.filedata = [NSMutableData new];
    }
    [self.filedata appendData:data];
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    self.imageVi.image = [UIImage imageWithData:self.filedata];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.progreess.progress = 0;
    self.imageVi.image = nil;
    attString = [[NSMutableAttributedString alloc] initWithString:@"%0.0"];
    [attString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(1, 3)];
    self.label.attributedText = attString;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
